import 'package:flutter/material.dart';
import 'package:pacsun/services/sysTagsService.dart' show SysTagsService;
import 'package:pacsun/utils/notifyMsg.dart' show notifyMsg;
import 'package:pacsun/model/userModel.dart' show UserModel;
import 'package:pacsun/model/sysUserTagModel.dart' show YouAreTagModel;

class SysTagsProvider with ChangeNotifier {
  //  [
  //   {
  //     "id": 1,
  //     "name": "Student"
  //   },
  //   {
  //     "id": 2,
  //     "name": "Content Creator"
  //   }
  // ],
  List<YouAreTagModel> _sysTags = []; // Initialize as empty list
  bool _isLoading = false;
  String? _error;

  List<YouAreTagModel> get sysTags => _sysTags;
  bool get isLoading => _isLoading;
  String? get error => _error;

  // Load system default tags
  Future<void> loadSystemTags() async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      // Get tags from service (already converted to YouAreTagModel)
      final List<YouAreTagModel> tags = await SysTagsService().getSysTags();

      // Update state with received tags
      _sysTags = tags;

      // Optional: If you want to ensure there's always content
      if (_sysTags.isEmpty) {
        // _sysTags = _getDefaultTags();
        _error = 'No tags received from server, using defaults';
      }
    } catch (e) {
      _error = 'Failed to load tags: ${e.toString()}';
      // Fallback to default tags
      // _sysTags = _getDefaultTags();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 1. Get a list of all tag names
  List<String> get tagNames {
    return _sysTags.map((tag) => tag.name).toList();
  }

  // 2. Get a comma-separated string of all tag IDs
  String get tagIdsString {
    return _sysTags.map((tag) => tag.id.toString()).join(',');
  }

  /// 1. Convert comma-separated string of tag IDs to a comma-separated string of tag names
  /// Example: "4,6,7" → "Grad Student, Nurse, Intern"
  String convertTagIdsToNames(String tagIds) {
    if (tagIds.isEmpty) return "";

    final ids = tagIds
        .split(',')
        .map((id) => int.tryParse(id.trim()))
        .whereType<int>()
        .toList();
    return _sysTags
        .where((tag) => ids.contains(tag.id))
        .map((tag) => tag.name)
        .join(', ');
  }

  /// 2. Convert list of tag names to comma-separated string of tag IDs
  /// Example: ["student", "normal"] → "5,6"
  String convertTagNamesToIds(List<String> tagNames) {
    if (tagNames.isEmpty) return '';

    return _sysTags
        .where((tag) => tagNames.contains(tag.name))
        .map((tag) => tag.id.toString())
        .join(',');
  }

  // Clear tags when logging out
  void clearTags() {
    _sysTags = [];
    notifyListeners();
  }
}
